﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.HtmlControls;
using GiveGraphMappers;
using GiveGraphModel;
using IOChannelLibraryExtensions;
using Microsoft.IdentityModel.Claims;
using Microsoft.IdentityModel.Protocols.WSFederation;
using Microsoft.IdentityModel.Web;
using WebApp.Models;
using WebApp.Util;
using Location = IOChannelLibraryExtensions.DataFormats.Location;

namespace WebApp.Controllers
{
    public class AccountController : Controller
    {
        private User GetSelf()
        {
            UserMapper mapper = new UserMapper();
            return mapper.Get(((IClaimsIdentity) User.Identity).GetUserId());
        }

        public ActionResult Index(int? id)
        {
            UserMapper mapper = new UserMapper();

            if (!((IClaimsIdentity)User.Identity).IsRegistered())
            {
                return View("Register");
            }

            if(id.HasValue)
            {
                return View("UserProfile", new Tuple<ViewUser, bool>(new ViewUser(mapper.Get(id.Value)), false));
            }

            if (User.IsUserInRole("Organization"))
                return View("InstitutionProfile", new Tuple<ViewOrganization, bool>(new ViewOrganization(new OrganizationMapper().Get(((IClaimsIdentity)User.Identity).GetUserId())), true));

            return View("UserProfile", new Tuple<ViewUser, bool>(new ViewUser(GetSelf()), true));
        }

        public ActionResult LogOut()
        {
            if (User.Identity.IsAuthenticated)
            {
                var fam = FederatedAuthentication.WSFederationAuthenticationModule;

                fam.SignOut(false);
                return View();
            }

            /*If we made it this far the front end has some real issues.*/
            return null;
        }

        public ActionResult LogIn()
        {
            if (!User.Identity.IsAuthenticated)
            {
                
                //Response.Redirect("https://givegraph.accesscontrol.windows.net:443/v2/wsfederation?wa=wsignin1.0&wtrealm=http%3a%2f%2fe6e405dc6e614f21adf1893e262cb28b.cloudapp.net%2f");
                Response.Redirect("https://givegraphacs.accesscontrol.appfabriclabs.com:443/v2/wsfederation?wa=wsignin1.0&wtrealm=http%3a%2f%2flocalhost%3a50630%2f");
            }

            //return View("UserProfile", new Tuple<ViewUser, bool>(new ViewUser(GetSelf()), true));
            return null;
        }

        public ActionResult Register(string country, string zipCode)
        {
            UserMapper mapper = new UserMapper();
            User user = new User {Country =  country, ZipCode = zipCode};

            var provider = (from p in ((IClaimsIdentity)User.Identity).Claims
                            where p.ClaimType.Equals("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider")
                            select p.Value).SingleOrDefault().ToLower();
            var email = (from p in ((IClaimsIdentity) User.Identity).Claims
                         where p.ClaimType == ClaimTypes.Email
                         select p.Value).SingleOrDefault();
            


            if (provider.Contains("google"))
                user.GoogleUserId = email;
            else if (provider.Contains("facebook"))
            {
                var fbtoken = (from p in ((IClaimsPrincipal) Thread.CurrentPrincipal).Identities[0].Claims
                               where p.ClaimType.Equals("http://www.facebook.com/claims/AccessToken")
                               select p.Value).DefaultIfEmpty("Unknown").Single();
                user.FacebookToken = Util.Utils.GetFacebookUserId(fbtoken).ToString();
                user.GoogleUserId = email;
            }
            mapper.Add(user);

            return Redirect("/Profile");
        }
    }
}
